<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      window.onload = () => {
        let arr = [
          { id: 1, name: '部门1', pid: 0 },
          { id: 11, name: '部门11', pid: 0 },
          { id: 4, name: '部门4', pid: 11 },
          { id: 5, name: '部门5', pid: 4 },
          { id: 2, name: '部门2', pid: 1 },
          { id: 3, name: '部门3', pid: 1 },
          { id: 12, name: '部门12', pid: 11 }
        ]
        /* function treeData(arr, pid, result) {
           for (const item of arr) {
             if (item.pid === pid) {
               const newItem = { children: [], ...item }
               result.push(newItem)
               treeData(arr, item.id, newItem.children)
             }
           }
         }
         let result = []
         treeData(arr, 0, result)
         console.log(result) */

        function treeData(arr) {
          const result = []
          const itemMap = {}
          for (const arrItem of arr) {
            itemMap[arrItem.id] = { ...arrItem, children: [] }
          }
          for (const arrItem of arr) {
            const id = arrItem.id
            const pid = arrItem.pid
            const treeItem = itemMap[id]
            if (pid === 0) {
              result.push(treeItem)
            } else {
              itemMap[pid].children.push(treeItem)
            }
          }
          return result
        }

        console.log(treeData(arr))
      }
    </script>
  </body>
</html>
